package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.pojo.Announcement;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.AnnouncementService;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.UsersApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.HuanXinUser;
import com.tanhua.dubbo.server.pojo.Users;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.MessageCommentVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.UserInfoVo;
import com.tanhua.server.vo.UsersVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author 王加鑫
 * @Date 2021/09/11 19:53
 * @Since JDK 1.8
 */
@Service
public class IMService {

    @Reference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    @Reference(version = "1.0.0")
    private UsersApi usersApi;

    @Autowired
    private UserInfoService userInfoService;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private AnnouncementService announcementService;

    /**
     * 根据环信用户名查询用户信息
     * @param userName
     * @return
     */
    public UserInfoVo queryUserInfoByUserName(String userName) {
        //根据环信用户名查询指定用户信息
        HuanXinUser huanXinUser = this.huanXinApi.queryUserByUserName(userName);
        if(ObjectUtil.isEmpty(huanXinUser)){
            return null;
        }
        //根据指定用户id查询该用户其余信息
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(huanXinUser.getUserId());
        if(ObjectUtil.isEmpty(userInfo)){
            return null;
        }

        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class, "marriage");
        userInfoVo.setGender(userInfo.getSex().getValue() == 1 ? "man":"woman");
        userInfoVo.setMarriage(userInfo.getMarriage().equals("已婚") ? 1:0);
        return userInfoVo;
    }

    /**
     * 添加好友
     * @param friendId
     * @return
     */
    public Boolean contactUser(Long friendId) {
        User user = UserThreadLocal.get();

        Boolean result = this.usersApi.saveUsers(user.getId(), friendId);
        if(result){
            return this.huanXinApi.addUserFriend(user.getId(),friendId);
        }
        return false;
    }

    /**
     * 查询好友列表
     * @param page
     * @param pageSize
     * @param keyword
     * @return
     */
    public PageResult queryContactsList(Integer page, Integer pageSize, String keyword) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        User user = UserThreadLocal.get();
        PageInfo<Users> pageInfo = this.usersApi.queryContactsList(page,pageSize,user.getId());
        List<Users> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }

        //获取当前用户所有好友的id
        List<Object> friendIds = CollUtil.getFieldValues(records, "friendId");
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id",friendIds);
        //对条件进行过滤
        if(ObjectUtil.isNotEmpty(keyword)){
            queryWrapper.like("nick_name",keyword);
        }

        //查询当前用户的所有好友的详细信息(昵称，头像等)
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByList(queryWrapper);
        if(CollUtil.isEmpty(userInfoList)){
            return pageResult;
        }

        List<UsersVo> usersVos = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            //将自己排除在好友列表之外
            if(userInfo.getUserId() == user.getId()){
                continue;
            }
            UsersVo usersVo = new UsersVo();
            usersVo.setId(userInfo.getUserId());
            usersVo.setAge(userInfo.getAge());
            usersVo.setAvatar(userInfo.getLogo());
            usersVo.setGender(userInfo.getSex().name().toLowerCase());
            usersVo.setNickname(userInfo.getNickName());
            //环信用户账号(根据环信username查询好友信息做准备)
            usersVo.setUserId("HX_" + userInfo.getUserId().toString());
            usersVo.setCity(userInfo.getCity());
            usersVos.add(usersVo);
        }
        pageResult.setItems(usersVos);

        return pageResult;
    }

    /**
     * 查询消息评论列表
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryUserCommentList(Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.queryLoveCommentListByUser(user.getId(), page, pageSize);
        return this.commonCommentList(pageInfo,page,pageSize);
    }

    /**
     * 查询消息喜欢列表
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryLoveCommentList(Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentListByUser(user.getId(), page, pageSize);
        return this.commonCommentList(pageInfo,page,pageSize);
    }

    /**
     * 查询消息点赞列表
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryLikeCommentList(Integer page, Integer pageSize) {
        User user = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.queryLikeCommentListByUser(user.getId(),page,pageSize);
        return this.commonCommentList(pageInfo,page,pageSize);
    }

    private PageResult commonCommentList(PageInfo<Comment> pageInfo,Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //根据userId,CommentType评论类型来查询出当前"评论表"的集合
        List<Comment> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }

        //获取评论人的id集合
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id",userIds);
        //根据用户id查询UserInfo表中数据
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByList(queryWrapper);
        if(CollUtil.isEmpty(userInfoList)){
            return pageResult;
        }
        List<MessageCommentVo> messageCommentVoList = new ArrayList<>();
        for (Comment record : records) {
            for (UserInfo userInfo : userInfoList) {
                if(record.getUserId() == userInfo.getUserId()){

                    MessageCommentVo messageCommentVo = new MessageCommentVo();
                    messageCommentVo.setId(record.getId().toHexString());
                    messageCommentVo.setAvatar(userInfo.getLogo());
                    messageCommentVo.setNickname(userInfo.getNickName());
                    messageCommentVo.setCreateDate(DateUtil.format(new Date(record.getCreated()), "yyyy-MM-dd HH:mm"));

                    messageCommentVoList.add(messageCommentVo);
                    break;
                }
            }
        }
        pageResult.setItems(messageCommentVoList);
        return pageResult;
    }

    /**
     * 查询公告列表
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryMessageAnnouncementList(Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        IPage<Announcement> announcementIPage = this.announcementService.queryList(page, pageSize);
        List<Announcement> records = announcementIPage.getRecords();
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }
        pageResult.setItems(records);
        return pageResult;
    }

    /**
     * 删除好友
     *
     * @param userId 好友id
     */
    public void removeUser(Long userId) {
        //删除好友关系
        User user = UserThreadLocal.get();
        Boolean result = this.usersApi.removeUsers(user.getId(), userId);
        if(result){
            //将环信平台的好友关系解除
            this.huanXinApi.removeUserFriend(user.getId(), userId);
        }
    }
}
